package com.web.main.exception;

import com.common.entity.Code;
import com.common.entity.ResponseResult;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * @create 2020-11-21 18:08
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    //admin的异常
    @ExceptionHandler
    public ResponseResult adminException(AdminException e) {
        return ResponseResult.error(Code.PARAM_ERROR).Message(e.getMessage());
    }

    //supplier的异常
    @ExceptionHandler
    public ResponseResult supplierException(SupplierException e) {
        return ResponseResult.error(Code.PARAM_ERROR).Message(e.getMessage());
    }

    //pile的异常
    @ExceptionHandler
    public ResponseResult pileException(PileException e) {
        return ResponseResult.error(Code.PARAM_ERROR).Message(e.getMessage());
    }

    //site的异常
    @ExceptionHandler
    public ResponseResult siteException(SiteException e) {
        return ResponseResult.error(Code.PARAM_ERROR).Message(e.getMessage());
    }

    //处理检验的异常
    @ExceptionHandler
    public ResponseResult validException(BindException e) {
        Map<String, String> collect = e.getBindingResult()
                .getFieldErrors()
                .stream()
                .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        return ResponseResult.error(Code.PARAM_ERROR).Data(collect);
    }

    //处理检验的异常。本来是这个捕获异常，但是不知道为什么捕获不到了。
    @ExceptionHandler
    public ResponseResult validException(MethodArgumentNotValidException e) {
        Map<String, String> collect = e.getBindingResult()
                .getFieldErrors()
                .stream()
                .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        return ResponseResult.error(Code.PARAM_ERROR).Data(collect);
    }

    //处理全局的异常。进入了上面的异常就不进下面的异常。
    @ExceptionHandler(RuntimeException.class)
    public ResponseResult globalException(RuntimeException e) {
        return ResponseResult.error(Code.UNKNOWN_Exception).Message(e.getMessage());
    }
}
